//
//  NetworkClient+Qiniu.swift
//  SitPosition
//
//  Created by apple on 2019/2/10.
//  Copyright © 2019 apple. All rights reserved.
//

import Foundation
import Qiniu


/**
 * 七牛相关接口
 */
extension NetworkApi {
    
    // 七牛配置
    public static func fetchOSSes() -> NetworkApi {
        return NetworkApi("/authentication/osses", method: .get)
    }
}

extension NetworkClient {
    
    // 七牛配置
    // 返回：QiniuBuckets
    func fetchOSSes(key: String,
                    type: QiniuBucketType,
                    success: DataParamCallback?,
                    failure: ErrorCallback?) {
        let params: [String : Any] = [
            "key": key,             // 上传七牛时的文件名
            "type": type.rawValue   // photo图片，video视频
        ]
        let completionHandler = commonDataRequestCompletion(success: success, failure: failure)
        NetworkClient.instance.request(NetworkApi.fetchOSSes(), params: params, headers: nil)
            .responseData(completionHandler: completionHandler)
    }
    
    // 上传图片
    func uploadImage(data: Data,
                     key: String,
                     token: String,
                     progress: @escaping (_ newProgress: Float) -> Void,
                     completion: @escaping (_ error: Error?) -> Void) {
        let configuration: QNConfiguration = QNConfiguration.build { (builder) in
            builder?.useHttps = false
            builder?.timeoutInterval = 30
            builder?.retryMax = 3
            if let folder = try? Paths.uploadCachePath(),
                let recorder = try? QNFileRecorder(folder: folder) {
                builder?.recorder = recorder
            }
        }
        let manager: QNUploadManager = QNUploadManager.sharedInstance(with: configuration)
        let options: QNUploadOption = QNUploadOption.init(progressHandler: { (key, percent) in
            progress(percent/100.0)
        })
        manager.put(data, key: key, token: token, complete: { (info, key, resp) in
            if (info?.isOK ?? false) {
                completion(nil)
            } else {
                completion(info?.error)
            }
        }, option: options)
    }
}
